﻿function SmithTabs(id, args) {
    var $d = document,
        ie = document.all ? true : false,
        that = this;
    function make(t, p, a, s, c) {
        var e = $d.createElement(t);
        if (a) { for (var i in a) e.setAttribute(i, a[i]); }
        if (s) { for (var i in s) e.style[i] = s[i]; }
        if (navigator && navigator.userAgent) {
            var g = navigator.userAgent;
            if (g.indexOf('MSIE 6.0') > 0 || g.indexOf('MSIE 7.0') > 0)
                e = $d.createElement(e.outerHTML.replace('\r\n', ''));
        }
        if (c) e.innerHTML = c;
        if (p) p.appendChild(e);
        return e;
    }
    function sc(o, c) {
        o.setAttribute('class', c);
        if (ie) o.setAttribute('className', c);
    }
    function rc(o) {
        o.removeAttribute('class');
        if (ie) o.removeAttribute('className');
    }
    this.id = id;
    this.p = { style: 'smithtabs', onselect: null };
    if (args) { for (var i in this.p) { if (args[i]) this.p[i] = args[i]; } }
    var e = $d.getElementById(id), tabs = [], tid = 0, tc = 0;
    if (!e) return null;
    var ctrl = make('div', e, { 'class': this.p.style });
    var h = make('ul', ctrl, { 'class': 'header' });
    var c = make('div', ctrl, { 'class': 'container' });
    this.getTab = function (i) { return tabs[i]; }
    this.select = function (i) {
        if (i < 0 && i >= tc) return;
        tid = i;
        for (var j = 0; j < h.childNodes.length; j++) {
            if (j == i) {
                sc(h.childNodes[j], 'select');
                c.childNodes[j].style.display = '';
            }
            else {
                rc(h.childNodes[j]);
                c.childNodes[j].style.display = 'none';
            }
        }
        if (that.p.onselect) that.p.onselect(that, tabs[i]);
    };
    this.append = function (id, header) {
        var t = {
            id: id,
            index: tc++,
            header: header,
            page: $d.getElementById(id)
        };
        var i = make('li', h);
        var a = make('a', i, { 'href': '#', 'hidefocus': '' }, null, header);
        a.onclick = function () { that.select(t.index); return false; }
        if (t.page) {
            t.page.parentNode.removeChild(t.page);
            c.appendChild(t.page);
            t.page.style.display = 'none';
        } else {
            t.page = make('div', c, { 'id': t.id });
        }
        tabs.push(t);
    };
    return this;
}